package com.binaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class BinaryTreePreorderTraversal0205_144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preorder(root,res);
        return res;
    }

    private void preorder(TreeNode root, List<Integer> res) {
        if(root == null) return;

        res.add(root.val);
        preorder(root.left,res);
        preorder(root.right,res);
    }
}


 class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;

     TreeNode() {
     }

     TreeNode(int val) {
         this.val = val;
     }

     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
  }


  //非递归（迭代）遍历
  class Preorder{
      public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>() ;
            if(root == null) return res;
            stack.push(root);
            while (!stack.isEmpty()){
                TreeNode pop = stack.pop();
//                if(pop != null) {
//                    if(pop.right != null) stack.push(pop.right);
//                    if(pop.left != null) stack.push(pop.left);
//                    stack.push(pop);
//                    stack.push(null);
//                }else {
//                    res.add(stack.pop().val);
//                }
                if(pop != null) res.add(pop.val);
                else continue;
                stack.push(pop.right);
                stack.push(pop.left);
            }
            return res;

      }
  }


  class PreorderT{
      public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        Stack<TreeNode> st = new Stack<>();
        if(root != null) st.push(root);
        while (!st.isEmpty()){
            TreeNode node = st.peek();
            if(node != null){
                st.pop();
                if(node.right != null) st.push(node.right);
                if(node.left != null) st.push(node.left);
                st.push(node);
                st.push(null);
            }else { // 只有遇到空节点的时候，才将下一个节点放进结果集
                st.pop();
                node =  st.pop();
                res.add(node.val);
            }
        }
        return res;
      }
  }
